﻿using System;
using System.Web;
using Microsoft.SharePoint;

namespace Eneta.Portal.Profiles
{
    public class EnetaProfileImageHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            var sizeString = request.QueryString["size"];
            var profile = EnetaProfilePage.GetCurrentProfile();
            int size;
            int.TryParse(sizeString, out size);

            switch(size)
            {
                case 16:
                case 32:
                case 64:
                    break;
                default:
                    size = 32;
                    break;
            }

            sizeString = size.ToString();

            var siteId = SPContext.Current.Site.ID;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb())
                    {
                        if (profile == null)
                            goto showDefault;
                        var list = web.Lists["ProfileList"];
                        var item = list.GetItemById(profile.Id);

                        sizeString = sizeString + "x" + sizeString;
                        foreach (string fileName in item.Attachments)
                        {
                            if (!fileName.Contains(sizeString))
                                continue;
                            var fileUrl = item.Attachments.UrlPrefix + fileName;
                            var file = web.GetFile(fileUrl);

                            var stream = file.OpenBinaryStream();
                            var bytes = new byte[stream.Length];

                            stream.Read(bytes, 0, bytes.Length);
                            stream.Dispose();

                            OutputImage(context, bytes);
                            response.End();
                            return;
                        }
                    showDefault:
                        var defaultFileUrl = "/Style Library/eneta/images/user.gif";
                        var defaultFile = web.GetFile(defaultFileUrl);
                        var defaultFileStream = defaultFile.OpenBinaryStream();
                        var defaultBytes = new byte[defaultFileStream.Length];

                        defaultFileStream.Read(defaultBytes, 0, defaultBytes.Length);
                        defaultFileStream.Dispose();
                        OutputImage(context, defaultBytes);
                        response.End();
                    }
                }
            }
                );
            SPSecurity.RunWithElevatedPrivileges(sec);
        }

        private void OutputImage(HttpContext context, byte[] imageBytes)
        {
            var response = context.Response;
            response.Clear();

            //response.Cache.SetExpires(DateTime.Now.AddSeconds(300));
            //response.Cache.SetCacheability(HttpCacheability.Private);

            response.ContentType = "image/png";
            response.AddHeader("Content-length", imageBytes.Length.ToString());
            response.BinaryWrite(imageBytes);
            response.Flush();
        }
    }
}